package com.huarun.http;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.Builder;
import java.net.http.HttpResponse;
import java.text.SimpleDateFormat;
import java.time.Duration;

import com.huarun.bean.HuaRunInfo;

public class RemoteHttpClientUtil {
	public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	private static RemoteHttpClientUtil instance = null;
	
	private RemoteHttpClientUtil() {
	}

	public static RemoteHttpClientUtil getInstance() {
		if (instance == null) {
			instance = new RemoteHttpClientUtil();
		}
		return instance;
	}
	
	public HuaRunInfo sendHttpGet(String httpUrl,HuaRunInfo huaRunInfo) throws Exception{
		HttpClient httpClient = huaRunInfo.getHttpClient();
		URI uri = new URI(httpUrl);
		Builder httpGetBuild = HttpRequest.newBuilder(uri);
		HttpRequest httpGetRequest = httpGetBuild.GET()
				.timeout(Duration.ofSeconds(10)).build();
		httpClient.sendAsync(httpGetRequest, HttpResponse.BodyHandlers.ofString())
        .whenComplete((resp,t) -> {
            if(t != null){
                t.printStackTrace();
            }else{
            	huaRunInfo.setContent(resp.body());
            }
        }).join();
        
		return huaRunInfo;
	}
	public  HuaRunInfo sendHttpPost(String httpUrl, HuaRunInfo huaRunInfo, String data) throws Exception{
        HttpClient httpClient = huaRunInfo.getHttpClient();
		URI uri = new URI(httpUrl);
		Builder httpGetBuild = HttpRequest.newBuilder(uri);
		HttpRequest httpPostRequest = httpGetBuild
				.timeout(Duration.ofSeconds(10))
                .POST(HttpRequest.BodyPublishers.ofString(data))
                .build();
		
		httpClient.sendAsync(httpPostRequest, HttpResponse.BodyHandlers.ofString())
        .whenComplete((resp,t) -> {
            if(t != null){
                t.printStackTrace();
            }else{
            	huaRunInfo.setContent(resp.body());
            }
        }).join();
        
		return huaRunInfo;
	}
}
